package org.linlinjava.litemall.admin.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.LogHelper;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.*;

@RestController
@RequestMapping("/admin/admin")
@Validated
public class AdminManageController {

    @Resource
    private LitemallAdminService adminService;
    @Resource
    private LogHelper logHelper;

    /**
     * 管理员列表
     */
    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员管理"},button = "查询")
    @GetMapping("/list")
    public Object adminList(String username,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer limit,
                            @Sort @RequestParam(defaultValue = "add_time") String sort,
                            @Order @RequestParam(defaultValue = "desc") String order){
        List<LitemallAdmin> adminList = adminService.querySelective(username, page, limit, sort, order);
        return ResponseUtil.okList(adminList);
    }

    /**
     * 验证格式
     */
    private Object validated(LitemallAdmin admin){
        if(StringUtils.isEmpty(admin.getUsername())){
            return ResponseUtil.badArgument();
        }
        if(StringUtils.isEmpty(admin.getPassword())||admin.getPassword().length()<6){
            return ResponseUtil.fail(ADMIN_INVALID_PASSWORD,"密码长度不能少于六位");
        }
        return null;
    }

    /**
     * 添加管理员
     */
    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员管理"},button = "添加")
    @PostMapping("/create")
    public Object createAdmin(@RequestBody LitemallAdmin admin){
        Object error = validated(admin);
        if(error != null){
            return error;
        }

        List<LitemallAdmin> adminList = adminService.findAdmin(admin.getUsername());
        if(adminList.size()>0){
            return ResponseUtil.fail(ADMIN_NAME_EXIST,"用户名已存在");
        }

        String password = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String passwordEncoder = encoder.encode(password);
        admin.setPassword(passwordEncoder);

        if(adminService.add(admin)){
            logHelper.logAuthSucceed("添加管理员成功",admin.getUsername());
            return ResponseUtil.ok(admin);
        }else{
            logHelper.logAuthFail("添加管理员失败",admin.getUsername());
            return ResponseUtil.fail();
        }
    }

    /**
     * 管理员详情
     */
    @RequiresPermissions("admin:admin:read")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员管理"},button = "详情")
    @GetMapping("/read")
    public Object adminInfo(@NotNull Integer id){
        LitemallAdmin admin = adminService.findById(id);
        return ResponseUtil.ok(admin);
    }

    /**
     * 编辑管理员
     */
    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员管理"},button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallAdmin admin){
        Object error = validated(admin);
        if(error != null){
            return error;
        }

        List<LitemallAdmin> adminList = adminService.findAdmin(admin.getUsername());
        LitemallAdmin checkAdmin = adminService.findById(admin.getId());

        if(adminList.size()>0){
            if(!checkAdmin.getUsername().equals(admin.getUsername())){
                return ResponseUtil.fail(ADMIN_NAME_EXIST,"名称已存在");
            }
        }

        admin.setPassword(null);

        if(adminService.updateById(admin)){
            logHelper.logAuthSucceed("编辑管理员成功",admin.getUsername());
            return ResponseUtil.ok(admin);
        }else{
            logHelper.logAuthFail("编辑管理员失败",admin.getUsername());
            return ResponseUtil.fail();
        }
    }

    /**
     * 删除管理员
     */
    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = {"系统管理","管理员管理"},button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallAdmin admin){
        Subject current = SecurityUtils.getSubject();
        LitemallAdmin currentAdmin = (LitemallAdmin)current.getPrincipal();
        if(currentAdmin.getId().equals(admin.getId())){
            return ResponseUtil.fail(ADMIN_DELETE_NOT_ALLOWED,"您不能删除自己的信息");
        }

        if(adminService.deleteById(admin.getId())){
            logHelper.logAuthSucceed("删除管理员成功",admin.getUsername());
            return ResponseUtil.ok();
        }else{
            logHelper.logAuthFail("删除管理员失败",admin.getUsername());
            return ResponseUtil.fail();
        }
    }

}
